<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\video\logic;
require_once '..'.DIRECTORY_SEPARATOR .'extend'.DIRECTORY_SEPARATOR .'alidb'.DIRECTORY_SEPARATOR .'aliyun-openapi-php-sdk-master'.DIRECTORY_SEPARATOR .'aliyun-php-sdk-core/Config.php';   // 假定您的源码文件和aliyun-php-sdk处于同一目录
/*require_once '/extend/alidb/voduploadsdk/Autoloader.php';*/
require_once dirname(dirname(dirname(__DIR__))) .DIRECTORY_SEPARATOR .'extend'.DIRECTORY_SEPARATOR .'alidb'.DIRECTORY_SEPARATOR .'voduploadsdk' . DIRECTORY_SEPARATOR . 'Autoloader.php';

use vod\Request\V20170321 as vod;
use Sts\Request\V20150401 as Sts;//STS专用

class Vodlogic{

    private $regionId           = 'cn-shanghai';// 点播服务接入区域

    private $accessKeyId        = 'LTAI4G9KPip2LSwWXN7XxcYe';
    private $accessKeySecret    = 'TVsIcAtwpteTVarJe4T1JqbkJD218x';
    //private $accessKeyId        = 'LTAI4FmtZLM3wactLdEi52tP';
    //private $accessKeySecret    = '4TcKFrb5s8ZwfOxHah3x4MxWMCQuA2';

    private $endpoint           = 'sts.cn-shanghai.aliyuncs.com';//STS专用

    /* private $regionId           = 'cn-shanghai';// 点播服务接入区域
    private $accessKeyId        = 'LTAI4GCKTNaEhCubwJWww9cw';
    private $accessKeySecret    = 'MmFiTFqKOI6bhL4O45unhiBkMeclIv';

    private $endpoint           = 'sts.cn-shanghai.aliyuncs.com';  */

    /**
     * 初始化
     * @param  
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    private function initVodClient(){
        try {
            $profile = \DefaultProfile::getProfile($this->regionId, $this->accessKeyId, $this->accessKeySecret);
            $client =  new \DefaultAcsClient($profile);
            return $client;
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
            //dump($e->getMessage());
        }
    }

    /**
     * 获取视频列表
     * @param  
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function getVideoList($status){
        try {
            $client =  $this -> initVodClient();
            $rel = $this -> getVideoListPri($client, $status);//die;
            $rel_arr = object2array($rel);
            return array_out(200, '获取成功', $rel_arr);
            
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
            //dump($e->getMessage());
        }
    }

    /**
     * 更新视频信息
     * @param  
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function updateVideoInfo($videoId, $title, $description, $cover_url){
        try {
            $client =  $this -> initVodClient();
            $request = new vod\UpdateVideoInfoRequest();
            $request->setVideoId($videoId);
            if($title) $request->setTitle($title);   // 更改视频标题
            if($description) $request->setDescription($description);    // 更改视频描述
            if($cover_url) $request->setCoverURL($cover_url);  // 更改视频封面
            //$request->setTags('tag1,tag2');    // 更改视频标签，多个用逗号分隔
            //$request->setCateId(0);       // 更改视频分类(可在点播控制台·全局设置·分类管理里查看分类ID：https://vod.console.aliyun.com/#/vod/settings/category)
            $request->setAcceptFormat('JSON');
            $rel = $client->getAcsResponse($request);
            $rel_arr = object2array($rel);
            return array_out(200, '获取成功', $rel_arr);
            
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
            //dump($e->getMessage());
        }
    }

    /**
     * 删除视频
     * @param  videoIds // 支持批量删除视频；videoIds为传入的视频ID列表，多个用逗号分隔 最多支持20个。
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function deleteVideos($videoIds){
        try {
            $client =  $this -> initVodClient();
            $request = new vod\DeleteVideoRequest();
            $request->setVideoIds($videoIds);   // 支持批量删除视频；videoIds为传入的视频ID列表，多个用逗号分隔
            $request->setAcceptFormat('JSON');
            $rel = $client->getAcsResponse($request);
            $rel_arr = object2array($rel);
            return array_out(200, '操作成功', $rel_arr);
            
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
            //dump($e->getMessage());
        }
    }

    /**
     * 提交智能审核作业 
     * @param  
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function submitAIMediaAuditJob($videoId){
        try {
            $client =  $this -> initVodClient();
            $request = new vod\SubmitAIMediaAuditJobRequest();
            // 设置视频ID
            $request->setMediaId($videoId);

            $rel = $client->getAcsResponse($request);
            $rel_arr = object2array($rel);

            //更新审核表字段为 智能审核中
            $map = [];
            $map['video_id'] = $VideoId;
            model('VideoPlayAiExamine') -> where($map)-> setField('examine_status', 1);

            return array_out(200, '获取成功', $rel_arr);
            
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
            //dump($e->getMessage());
        }
    }

    /**
     * 提交 人工审核作业 
     * @param  videoId 视频标识
     * @param  Status Blocked(屏蔽) Normal(正常)
     * @param  Reason 若审核状态为屏蔽时，需给出屏蔽的理由，最长支持128字节。
     * @param  Comment 审核备注
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function buildAuditContent($array_video){//($videoId, $Status, $Reason='', $Comment=''){
        try {
            $client =  $this -> initVodClient();
            $request = new vod\CreateAuditRequest();
            // 设置审核内容
            $request->setAuditContent(json_encode($array_video));

            $rel = $client->getAcsResponse($request);
            $rel_arr = object2array($rel);
            return array_out(200, '操作成功', $rel_arr);
            
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
            //dump($e->getMessage());
        }
    }

    /**
     * 获取视频列表
     * @param client 发送请求客户端
     * @return GetVideoListResponse 获取视频列表响应数据
     */
    private function getVideoListPri($client, $status) {
        $request = new vod\GetVideoListRequest();//dump($request);die;
        // 示例：分别取一个月前、当前时间的UTC时间作为筛选视频列表的起止时间
        $localTimeZone = date_default_timezone_get();
        date_default_timezone_set('UTC');
        $utcNow = gmdate('Y-m-d\TH:i:s\Z');
        $utcMonthAgo = gmdate('Y-m-d\TH:i:s\Z', time() - 30*86400);
        date_default_timezone_set($localTimeZone);
        $request->setStartTime($utcMonthAgo);   // 视频创建的起始时间，为UTC格式
        $request->setEndTime($utcNow);          // 视频创建的结束时间，为UTC格式
        if($status) $request->setStatus($status);  // 视频状态，默认获取所有状态的视频，多个用逗号分隔
        #$request->setStatus('Uploading,Normal,Transcoding');  // 视频状态，默认获取所有状态的视频，多个用逗号分隔
        #$request->setCateId(0);               // 按分类进行筛选
        $request->setPageNo(1);
        $request->setPageSize(20);
        $request->setAcceptFormat('JSON');
        return $client->getAcsResponse($request);
    }


    /**
     * STS上传凭证
     * @param  
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function createUploadVideoReque1st(){
        try {
            // 只允许 RAM 用户使用角色
            \DefaultProfile::addEndpoint($this->regionId, $this->regionId, "Sts", $this->endpoint);
            $iClientProfile = \DefaultProfile::getProfile($this->regionId, $this->accessKeyId, $this->accessKeySecret);
            $client = new \DefaultAcsClient($iClientProfile);
            // 指定角色 ARN
            $roleArn = "acs:ram::31870735:role/xiangmushipin";
            // 在扮演角色时，添加一个权限策略，进一步限制角色的权限
            // 以下权限策略表示拥有可以读取所有 OSS 的只读权限
             $policy=<<<POLICY
            {
            "Statement": [
                {
                "Action": [
                    "vod:CreateUploadVideo",
                    "vod:UpdateVideoInfo"
                ],
                "Effect": "Allow",
                "Resource": "*"
                }
            ],
            "Version": "1"
            }
            POLICY; 
            $request = new Sts\AssumeRoleRequest();
            // RoleSessionName 即临时身份的会话名称，用于区分不同的临时身份
            $request->setRoleSessionName("client_name");
            $request->setRoleArn($roleArn);
            $request->setPolicy($policy);
            $request->setDurationSeconds(3600);
            $response = $client->getAcsResponse($request);
            $rel_arr  = object2array($response);
            return array_out(200, '获取成功', $rel_arr);
            
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
            //dump($e->getMessage());
        }
    }

	/**
     * 创建视频上传凭证
     * @param  
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function createUploadVideoRequest($title, $file_name, $description='', $cover_url='', $tags='', $file_size='', $play_type=''){
        try {
            $client =  $this -> initVodClient();
            $rel = $this -> createUploadVideo($client, $title, $file_name, $description, $cover_url, $tags, $file_size, $play_type);
            $rel_arr = object2array($rel);
            return array_out(200, '获取成功', $rel_arr);
            
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
            //dump($e->getMessage());
        }
    }

    /**
     * 提交媒体处理作业
     * @param  
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function submitTranscodeJobs($videoid, $templateid){
        try {
            $client =  $this -> initVodClient();
            $request = new vod\SubmitTranscodeJobsRequest();
            //需要转码的视频ID
            $request->setVideoId($videoid);
            //转码模板ID
            $request->setTemplateGroupId($templateid);
            //构建需要替换的水印参数(只有需要替换水印相关信息才需要构建)
            //$request->setOverrideParams(buildOverrideParams());
            //HLS标准加密配置(只有标准加密才需要传递)
            //$request->setEncryptConfig(buildEncryptConfig($client));
            $rel =  $client->getAcsResponse($request);
            $rel_arr = object2array($rel);
            return array_out(200, '获取成功', $rel_arr);
            
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
            //dump($e->getMessage());
        }
    }

    /**
     * 刷新视频上传凭证
     * @param  object $videoId  视频标识
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function refreshUploadVideoRequest($videoId){
        try {
            $client =  $this -> initVodClient();
            $rel = $this -> refreshUploadVideo($client, $videoId);
            $rel_arr = object2array($rel);
            return array_out(200, '获取成功', $rel_arr);
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
            //dump($e->getMessage());
        }
    }

    /**
     * 获取视频详情
     * @param  object $videoId  视频标识
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function getPlayInfo($videoId, $timeout = 3600*24){
        try {
            $client =  $this -> initVodClient();
            $rel = $this -> getPlayInfoPrivate($client, $videoId, $timeout);
            $rel_arr = object2array($rel);//dump($rel_arr);
            if(isset($rel_arr['VideoBase'])){
                return array_out(200, '获取成功', $rel_arr);
            }else{
                return array_out(-1005, '获取失败', $rel_arr);
            }
           
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
            //dump($e->getMessage());
        }
    }

    /**
     * 获取播放凭证
     * @param  object $videoId  视频标识
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    public function getVideoPlayAuth($videoId){
        try {
            $client =  $this -> initVodClient();
            $rel = $this -> getPlayAuth($client, $videoId);
            $rel_arr = object2array($rel);
            if(isset($rel_arr['code']) == -9999){
                return array_out(-1005, $rel_arr['message']);
            }else{
                return array_out(200, '获取成功', $rel_arr);
            }
            
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
            //dump($e->getMessage());
        }
    }

    /**
     * 获取播放凭证
     * @param  object $client  初始化
     * @param  object $videoId  视频标识
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    private function getPlayAuth($client, $videoId){
        try {
            $request = new vod\GetVideoPlayAuthRequest();
            $request->setVideoId($videoId);
            $request->setAuthInfoTimeout(3000);//播放凭证时间
            $request->setAcceptFormat('JSON');
            $response = $client->getAcsResponse($request);
            return $response;
        } catch (\Exception $e) {
            return array_out(-9999, $e->getMessage());
        }
    }

    /**
     * 获取播放地址
     * @param  object $client  初始化
     * @param  object $videoId  视频标识
     * @author jason wang <120907037@qq.com>
     * @return mixed
     */
    private function getPlayInfoPrivate($client, $videoId, $timeout = 3600*24){
        $request = new vod\GetPlayInfoRequest();
        $request->setVideoId($videoId);
        $request->setAuthTimeout($timeout);
        $request->setAcceptFormat('JSON');
        return $client->getAcsResponse($request);
    }


    /**
     * 获取视频上传地址和凭证
     * @param client 发送请求客户端
     * @param title string 视频标题
     * @param file_name string 文件名称
     * @param description string 视频描述
     * @param coverUrl string 视频截图
     * @param tags string 标签
     * @param file_size int 文件大小
     * @return CreateUploadVideoResponse 获取视频上传地址和凭证响应数据
     */
    private function createUploadVideo($client, $title, $file_name, $description, $coverUrl = '', $tags='', $file_size, $play_type) {//
        switch ($play_type) {
            case 1://短视频
                $cateId = '1000174414';
                break;
            case 2://长视频
                $cateId = '1000174413';
                break;
            default://测试视频
                $cateId = '1000174415';
                break;
        }
        $request = new vod\CreateUploadVideoRequest();
        if($title) $request->setTitle($title);        
        if($file_name) $request->setFileName($file_name); 
        if($description) $request->setDescription($description);
        if($cateId) $request->setCateId($cateId);//测试分类
        //$request->FileSize($file_size);
        if($coverUrl) $request->setCoverURL($coverUrl); 
        if($tags) $request->setTags($tags);
        //$request->setWorkflowId('778765e22d3a2ce1bb131dcc09ec34f2');//工作流
        $request->setAcceptFormat('JSON');
        return $client->getAcsResponse($request);
    }

    /**
     * 刷新视频上传凭证
     * @param client 发送请求客户端
     * @param  object $client  发送请求客户端初始化
     * @param  object $videoId  视频标识
     * @return RefreshUploadVideoResponse 刷新视频上传凭证响应数据
     */
    private function refreshUploadVideo($client, $videoId) {
        $request = new vod\RefreshUploadVideoRequest();
        $request->setVideoId($videoId);
        $request->setAcceptFormat('JSON');
        return $client->getAcsResponse($request);
    }

    /**
     * 视频剪辑
     * @param client 发送请求客户端
     * @param  object $client  发送请求客户端初始化
     * @param  object $videoId  视频标识
     * @return RefreshUploadVideoResponse 刷新视频上传凭证响应数据
     */
    public function vodClip($videoId, $title, $description) {
        try {
            $client =  $this -> initVodClient();
            $request = new vod\ProduceEditingProjectVideoRequest();
            // Set Produce Media Metadata
            $request->setMediaMetadata($this -> buildMediaMetadata($title, $description));
            // Set Produce Configuration
            $request->setProduceConfig($this -> buildProduceConfig());
            // Build Editing Project Timeline
            $request->setTimeline($this -> buildTimeline($videoId));
            // Get result
            $result = $client->getAcsResponse($request);
            $rel_arr = object2array($result);
            return array_out(200, '获取成功', $rel_arr);
            var_dump($result);
       } catch (Exception $e) {
           print $e->getMessage()."\n";
       }
    }

    //视频剪辑
    private function buildMediaMetadata($title, $description) {
        $mediaMetadata = array();
        // Produce Media Title
        $mediaMetadata['Title'] = $title;
        // Produce Media Description
        $mediaMetadata['Description'] = $description;
        // Produce Media UserDefined Cover URL
        //$mediaMetadata['CoverURL'] = 'http://test.testvod123.com/media/cover/mediaid.jpg';
        // Produce Media Category ID
        $mediaMetadata['CateId'] = '1000138906';//长视频剪辑
        // Produce Media Category Name
        //$mediaMetadata['Tags'] = 'Tag1,Tag2,Test';
        return json_encode($mediaMetadata);
    }

    //视频剪辑
    private function buildProduceConfig() {
        $produceConfig = array();
        /*
         The produce process can generate media mezzanine file. You can use the mezzanine file to transcode other media files，just like the transcode process after file upload finished. This field describe the Transocde TemplateGroup ID after produce mezzanine finished.
         1. Not required
         2. Use default transcode template group id when empty
         */
        $produceConfig['TemplateGroupId'] = null;
        return json_encode($produceConfig);
    }

    //视频剪辑
    private function buildTimeline($videoId) {
        $timeline = array();
        // Video Track
        $videoTracks = array();
        $videoTrack = array();
        // Video Track Clicps
        $videoTrackClips = array();
        $videoTrackClip1 = array();
        $videoTrackClip1['MediaId'] = $videoId;
        $videoTrackClip1['In'] = 0;
        $videoTrackClip1['Out'] = 59;
        $videoTrackClips[] = $videoTrackClip1;
        /* $videoTrackClip2 = array();
        $videoTrackClip2['MediaId'] = '070bbc13d8294e35b36c3e7abxxxxxx';
        $videoTrackClips[] = $videoTrackClip2; */
        $videoTrack['VideoTrackClips'] = $videoTrackClips;
        $videoTracks[] = $videoTrack; 
        $timeline['VideoTracks'] = $videoTracks;
        return json_encode($timeline);
    }


    /**
     * 后端使用-视频上传接口
     * @param $filePath
     * @author dou <51779987@qq.com>
     * @return array
     * @throws \Exception
     */
    function testUploadLocalVideo($filePath,$video_id=false)
    {
        try {
            $uploader = new \AliyunVodUploader($this->accessKeyId, $this->accessKeySecret);
            $uploadVideoRequest = new \UploadVideoRequest($filePath, 'testUploadLocalVideo via PHP-SDK');
            //$uploadVideoRequest->setCateId(1);
            //$uploadVideoRequest->setCoverURL("http://xxxx.jpg");
            //$uploadVideoRequest->setTags('test1,test2');
            //$uploadVideoRequest->setStorageLocation('outin-xx.oss-cn-beijing.aliyuncs.com');
            //$uploadVideoRequest->setTemplateGroupId('6ae347b0140181ad371d197ebe289326');
            //$callback_url = 'http://120.79.181.163/muxiaopu/public/index.php/video/publics/video_callback';
            $callback_url = 'https://appapi.mushop.live/public/index.php/video/publics/video_callback';
            //$callback_url = $_SERVER['HTTP_HOST'].url('publics/video_callback');
            //trace($callback_url, 'input_params');
            $userData = array(
                "MessageCallback"=>array("CallbackURL"=>$callback_url),
            );
            $uploadVideoRequest->setUserData(json_encode($userData));
            //获取videoId  后 异步上传视频
            //$res = $uploader->uploadLocalVideo($uploadVideoRequest);
            //dump($video_id);
            if($video_id){
                //日志 记录
                trace($video_id, 'input_params');
                $uploadInfo = $uploader->refreshUploadVideo($video_id);//dump($uploadInfo);
                //日志 记录
                $body = json_encode($uploadInfo, true);
                trace($body, 'input_params');
                $res = $uploader->uploadLocalVideoDemo($uploadVideoRequest,$uploadInfo);//dump($res);
                trace($res, 'input_params');
                $body = json_encode($res, true);
                trace($body, 'input_params');
            }else{
                $res = $uploader->uploadLocalVideoId($uploadVideoRequest);
                $rel_arr = object2array($res);
                return array_out(200, '上传视频成功', $rel_arr);
            }
        } catch (\Exception $e) {
            dump($e->getMessage());
            trace($e->getMessage(), 'input_params');
            printf("testUploadLocalVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
                $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
        }
    }


    function testUploadLocalVideoDemo($filePath)
    {
        try {
            $uploader = new \AliyunVodUploader($this->accessKeyId, $this->accessKeySecret);
            $uploadVideoRequest = new \UploadVideoRequest($filePath, 'testUploadLocalVideo via PHP-SDK');
            //$uploadVideoRequest->setCateId(1);
            //$uploadVideoRequest->setCoverURL("http://xxxx.jpg");
            //$uploadVideoRequest->setTags('test1,test2');
            //$uploadVideoRequest->setStorageLocation('outin-xx.oss-cn-beijing.aliyuncs.com');
            //$uploadVideoRequest->setTemplateGroupId('6ae347b0140181ad371d197ebe289326');
            //$callback_url = 'http://120.79.181.163/muxiaopu/public/index.php/video/publics/video_callback';
            $callback_url = 'https://appapi.mushop.live/public/index.php/video/publics/video_callback';
            $userData = array(
                "MessageCallback"=>array("CallbackURL"=>$callback_url),
                //"Extend"=>array("localId"=>"xxx", "test"=>"www")
            );
            $uploadVideoRequest->setUserData(json_encode($userData));
            $res = $uploader->uploadLocalVideo($uploadVideoRequest);
            $rel_arr = object2array($res);
            return array_out(200, '上传视频成功', ['VideoId' => $rel_arr]);
        } catch (Exception $e) {
            printf("testUploadLocalVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
                $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
        }
    }

}